package dimension.starry.block.loot;

import dimension.starry.block.typeInterface.LootChest;
import dimension.starry.dataManager.LootChestDataManager;
import dimension.starry.loot.NormalLoots;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BarrelBlockEntity;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.mob.PiglinBrain;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.stat.Stats;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

public class NormalLootChest extends LootChest {

    @Override
    public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
        if (world.isClient) {
            return ActionResult.SUCCESS;
        } else {
            BlockEntity blockEntity = world.getBlockEntity(pos);
            if (blockEntity instanceof BarrelBlockEntity barrelBlockEntity) {
                if (!LootChestDataManager.containsAndAddPlayerIfAbsent((ServerWorld) world, pos, player.getName().getString())) {
                    for (int i = 0; i < 27; i++) {
                        barrelBlockEntity.setStack(i, new ItemStack(NormalLoots.getRandomItem()));
                    }
                }
                player.openHandledScreen(barrelBlockEntity);
                player.incrementStat(Stats.OPEN_BARREL);
                PiglinBrain.onGuardedBlockInteracted(player, true);
            }

            return ActionResult.CONSUME;
        }
    }
}
